﻿using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Tasks;
using TradeMeSDK;

namespace TradeMo
{
	public interface IListingView
	{
		void GotoState(string stateName, bool useTransitions);
	}

    public partial class ListingView : IListingView
    {
        private readonly ListingViewModel _viewModel;

        public ListingView()
        {
            InitializeComponent();
            _viewModel = new ListingViewModel {View = this};
        	DataContext = _viewModel;
            AnimationContext = LayoutRoot;
        	VisualStateManager.GoToState(this, "LoadingState", false);
        }

    	public void GotoState(string stateName, bool useTransitions)
		{
            UpdatePivot();
            VisualStateManager.GoToState(this, stateName, useTransitions);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (_viewModel.ListingId != 0)
            {
                _viewModel.LoadedAgain();
                GotoState("LoadedState", false);
                return; // already loaded
            }

            string id;
            if (!NavigationContext.QueryString.TryGetValue("ListingId", out id))
                NavigationService.GoBack();
            _viewModel.ListingId = Convert.ToInt32(id);
        }

        private void UpdatePivot()
        {
            if (_viewModel.Listing == null) return;

            if (_viewModel.IsJob || _viewModel.IsProperty)
            {
                pivot.Items.Remove(HistoryPivotItem);
                pivot.Items.Remove(BidPivotItem);
            }

            if ((_viewModel.Listing.Photos == null) ||
                (_viewModel.Listing.Photos.Count == 0))
            {
                pivot.Items.Remove(PhotoPivotItem);
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (_viewModel.AskingQuestion || _viewModel.ShowingTrial)
            {
                e.Cancel = true;
            	_viewModel.AskingQuestion = false;
                _viewModel.ShowingTrial = false;
                VisualStateManager.GoToState(this, "NoPopup", true);
                TradeMeDispatcher.OnUIThread(200, () =>
                            {
                                TrialModeBorder.Visibility = Visibility.Collapsed;
                                AskQuestionBorder.Visibility = Visibility.Collapsed;
                            });
                return;
            }
            base.OnBackKeyPress(e);
        }

        private void ImageList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var photo = ImageList.SelectedItem as Photo;
            if (photo == null) return;

            NavigationService.Navigate(new Uri("/ImagePage.xaml?picture=" + photo.Value.FullSize, UriKind.Relative));
            ImageList.SelectedItem = null;
        }

        private void Breadcrumbs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Breadcrumbs.SelectedItem == null) return;
            var breadcrumb = Breadcrumbs.SelectedItem as Category;
            Breadcrumbs.SelectedItem = null;
            if (breadcrumb == null) return;


            var criteria = App.Model.GeneralSearchCriteriaModel.Criteria.Clone();
            criteria.SearchString = null;
            criteria.Category = breadcrumb.Number;

            string hash = criteria.GetHashCode().ToString();
            new IsolatedStorageRepository<SearchGeneralCriteria>(hash + ".criteria").Write(criteria);

            NavigationService.Navigate(new Uri("/SearchResultsView.xaml?type=category&criteria=" + hash,
                                               UriKind.Relative));
        }

        private void BidButton_Click(object sender, RoutedEventArgs e)
        {
            if (!App.TradeMe.IsLoggedIn)
            {
                NavigationService.Navigate(new Uri("/TradeMeLoginView.xaml", UriKind.Relative));
                return;
            }
            _viewModel.Bid();
        }

        private void AddWatchListButton_Click(object sender, RoutedEventArgs e)
        {
            if (!App.TradeMe.IsLoggedIn)
            {
                NavigationService.Navigate(new Uri("/TradeMeLoginView.xaml", UriKind.Relative));
                return;
            }
            _viewModel.UpdateWatchList();
        }

        private void AskQuestionButton_Click(object sender, RoutedEventArgs e)
        {
            if (!App.TradeMe.IsLoggedIn)
            {
                NavigationService.Navigate(new Uri("/TradeMeLoginView.xaml", UriKind.Relative));
                return;
            }
        	_viewModel.AskingQuestion = true;
        	AskQuestionBorder.Visibility = Visibility.Visible;
            VisualStateManager.GoToState(this, "AskQuestionState", true);
        }

        private void CancelQuestionButton_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.Question = "";
            VisualStateManager.GoToState(this, "NoPopup", true);
			TradeMeDispatcher.OnUIThread(200, () => AskQuestionBorder.Visibility = Visibility.Collapsed);
        }

        private void SubmitQuestionButton_Click(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "NoPopup", true);
			TradeMeDispatcher.OnUIThread(200, () => AskQuestionBorder.Visibility = Visibility.Collapsed);
            _viewModel.SubmitQuestion();
        }

        private void BuyNowButton_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.BuyNow();
        }

        private void LaunchListingButton_Click(object sender, RoutedEventArgs e)
        {
        	WebBrowserTask task = new WebBrowserTask
        	                      	{
        	                      		URL = TradeMeConstants.FullListingUrl + _viewModel.ListingId
        	                      	};
        	task.Show();
        }

        private void DealerButton_Click(object sender, RoutedEventArgs e)
        {
			if ((_viewModel.Listing == null) ||
				(_viewModel.Listing.Dealership == null) ||
				string.IsNullOrEmpty(_viewModel.Listing.Dealership.Website))
				return;

        	WebBrowserTask task = new WebBrowserTask
        	                      	{
        	                      		URL = _viewModel.Listing.Dealership.Website
        	                      	};
			task.Show();
        }

		private void AgencyButton_Click(object sender, RoutedEventArgs e)
		{
			if ((_viewModel.Listing == null) ||
				(_viewModel.Listing.Agency == null) ||
				string.IsNullOrEmpty(_viewModel.Listing.Agency.Website))
				return;

			WebBrowserTask task = new WebBrowserTask
			{
				URL = _viewModel.Listing.Agency.Website
			};
			task.Show();
		}

        private void ContinueTrialButton_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.ShowingTrial = false;
            VisualStateManager.GoToState(this, "NoPopup", true);
            TradeMeDispatcher.OnUIThread(200, () => TrialModeBorder.Visibility = Visibility.Collapsed);
        }

        private void BuyButton_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.ShowingTrial = false;
            VisualStateManager.GoToState(this, "NoPopup", true);
            TradeMeDispatcher.OnUIThread(200, () => TrialModeBorder.Visibility = Visibility.Collapsed);

            _detailTask.Show();
        }

        private MarketplaceDetailTask _detailTask = new MarketplaceDetailTask();
    }
}